import React, { useState, useEffect, useCallback, useContext } from "react";
import { getBcxtWxUserMhOaLogin } from '../../Api/loginUrl';
import {myContext} from '../../reducer'
//引入路由
import UserRoutes from "../../Route";
//合同侧边栏
import { menuLeftContractRouter } from '../Contract/ContractRouter';
//生产管理侧边栏
import { enumLeftProductionPlan } from '../ProductionPlan/router';
//财务管理侧边栏
import { menuFinancialModule } from '../FinancialManagementModule/router';
//门禁侧边栏
import { enumLeftAccessControl } from "../AccessControl/router";
import {
    menuTopRouter,
    menuLeftUserRouter,
    meunParkMessageRouter,
    menuLeftClientRouter,// 客户管理
    menuLeftProductionRouter,
    menuLeftPersonnelRouter, // 设置中心
    menuFinancial, //费用管理侧边栏
} from "../../Route/routes";


//报餐管理侧边栏
import { enumLeftAddMeal } from '../AddMeal/router';

import { useHistory, useLocation } from "react-router-dom";
import { HomeAllBOx, HomeMessage, HomeHeaderConter } from "./style";
//component
import HomeNav from "./components/HomeNav";
import HomeContent from '../HomeContent'
//antd
import { Layout, Menu, Space, Button, message } from "antd";
const { Header, Content, Sider } = Layout;

/**
 * @description: 公共组件页面 - 主要是菜单
 * @author: xiaoxujs
 * @updata: xiaoxujs(2021-09-08) 菜单添加权限判断
 */

const Home = () => {
    const history = useHistory();
    const location = new useLocation();
    const contentHeight = window.innerHeight - 64 - 24;
    const { dispatch } = useContext(myContext)
    const [menuLeftData, setMenuLeftData] = useState([]); //侧边栏导航路径
    const [topKey, setTopKey] = useState('1'); //侧边栏导航路径
    const [menuList, setMenuList] = useState([]); //权限之后列表数据
    const setMenu = useCallback(
        (sessionViewPer, val, newNewVal) => {
            sessionViewPer.forEach(element => {
                //一级菜单
                val.forEach((item, index) => {
                    if (element === item.authority) {
                        if (item.page) {
                            newNewVal[index] = {
                                ...item,
                                page: []
                            }
                            setMenu(sessionViewPer, item.page, newNewVal[index].page);
                        } else {
                            newNewVal[index] = {
                                ...item
                            }
                        }
                    }
                });
            });
        },
        [],
    )
    const handleChangeToken = useCallback(
        (path) => {
            if (path === '/addMeal/noticeList') {
                const token = sessionStorage.getItem('token')
                    ; (async () => {
                        const { code, msg, data } = await getBcxtWxUserMhOaLogin({ mhOaToken: token });
                        if (code === "20000") {
                            sessionStorage.setItem('wxToken', data.token);
                            dispatch({ type: 'tokenType', value: 2 })
                        } else {
                            message.error(msg);
                        }
                    })()
            } else {
                sessionStorage.removeItem('wxToken');
                dispatch({ type: 'tokenType', value: 1 })
            }
        },
        [dispatch],
    )
    useEffect(() => {
        const sessionViewPer = JSON.parse(sessionStorage.getItem('viewPer'));
        let newMenu = [];
        sessionViewPer.forEach(element => {
            //一级菜单
            menuTopRouter.forEach(item => {
                if (element === item.authority) {
                    newMenu.push(item)
                }
            });
        });
        //权限判断
        setMenuList(newMenu);
        const sessionValue = sessionStorage.getItem('topKey')
        if (sessionValue) {
            setTopKey(sessionValue);
            let menuList = [];
            switch (sessionValue) {
                case 'clues': //线索
                    setMenuLeftData(menuLeftUserRouter);
                    break;
                case 'client': //客户管理
                    setMenu(sessionViewPer, menuLeftClientRouter, menuList);
                    break;
                case 'park': //停车场
                    setMenuLeftData(meunParkMessageRouter);
                    break;
                case 'production': //停车场
                    setMenuLeftData(menuLeftProductionRouter);
                    break;
                case 'personnel': //设置中心
                    setMenu(sessionViewPer, menuLeftPersonnelRouter, menuList);
                    break;
                case 'todoList': //费用管理
                    setMenu(sessionViewPer, menuFinancial, menuList);
                    break;
                case 'signContract': //合同管理
                    setMenu(sessionViewPer, menuLeftContractRouter, menuList);
                    break
                case 'financiaManagementModule': //财务管理
                    setMenu(sessionViewPer, menuFinancialModule, menuList);
                    break;
                case 'productionPlan': //生产计划
                    setMenu(sessionViewPer, enumLeftProductionPlan, menuList);
                    break;
                case 'accessControl': //门禁管理
                    setMenu(sessionViewPer, enumLeftAccessControl, menuList);
                    break;
                case 'addMeal': //报餐管理
                    setMenu(sessionViewPer, enumLeftAddMeal, menuList);
                    break;
                default:
                    setMenuLeftData(menuLeftProductionRouter);
            }
            setMenuLeftData(menuList);
        } else {
            setTopKey('Home');
            setMenuLeftData(menuLeftProductionRouter);
        }
        // setMenuLeftData(menuLeftUserRouter);
    }, [setMenu]);

    //头部导航页面跳转
    const handleEnterPage = (path, key) => {
        const sessionViewPer = JSON.parse(sessionStorage.getItem('viewPer'));
        let menuList = [];
        console.log()
        handleChangeToken(path);
        switch (path) {
            case '/clues/customer/await': //客户线索
                setMenuLeftData(menuLeftUserRouter);
                break;
            case '/production': //营销管理
                setMenuLeftData(menuLeftProductionRouter);
                break;
            case '/company/client/index': //客户管理
                setMenu(sessionViewPer, menuLeftClientRouter, menuList);
                break;
            case '/parkMessage':
                setMenuLeftData(meunParkMessageRouter);
                break;
            case '/personnel/all/management/list': //设置中心
                setMenu(sessionViewPer, menuLeftPersonnelRouter, menuList);
                break;
            case '/todoListAll': //费用管理
                setMenu(sessionViewPer, menuFinancial, menuList);
                break;
            case '/signContract': //合同管理
                setMenu(sessionViewPer, menuLeftContractRouter, menuList);
                break;
            case '/actualMoney': //财务管理
                setMenu(sessionViewPer, menuFinancialModule, menuList);
                break;
            case '/planing': //生产计划
                setMenu(sessionViewPer, enumLeftProductionPlan, menuList);
                break;
            case '/noticeList': //门禁管理
                setMenu(sessionViewPer, enumLeftAccessControl, menuList);
                break;
            case '/addMeal/noticeList': //报餐管理
                setMenu(sessionViewPer, enumLeftAddMeal, menuList);
                break;
            default:
                setMenuLeftData(menuLeftUserRouter);
        }

        setMenuLeftData(menuList);
        setTopKey(key);
        sessionStorage.setItem('topKey', key)
        history.push(path);
    };
    //退出
    const handleExit = () => {
        sessionStorage.removeItem('token');
        sessionStorage.removeItem('topKey');
        sessionStorage.removeItem('wxToken');
        history.push('/login');
    }
    return (
        <HomeAllBOx>
            <Layout>
                <Header className="header">
                    <div className="logo">
                        煤化OA系统
                    </div>
                    <HomeHeaderConter>
                        <Menu theme="dark" mode="horizontal" defaultSelectedKeys={["1"]} selectedKeys={[topKey]}>
                            {menuList
                                ? menuList.map((item) => {
                                    return (
                                        <Menu.Item
                                            key={item.key}
                                            onClick={() => handleEnterPage(item.path, item.key)}
                                        >
                                            {item.meta.title}
                                        </Menu.Item>
                                    );
                                })
                                : null}
                        </Menu>
                    </HomeHeaderConter>
                    <HomeMessage>
                        <Space>
                            <Button type="primary" onClick={handleExit}>退出登录</Button>
                        </Space>
                    </HomeMessage>

                </Header>
                {
                    location.pathname === '/'
                        ?
                        <Layout>
                            <HomeContent />
                        </Layout>
                        :
                        <Layout>
                            <Sider width={200} className="site-layout-background">
                                <HomeNav menuData={menuLeftData} />
                            </Sider>
                            <Layout style={{ background: "#F2F2F2" }}>
                                <Content
                                    className="site-layout-background"
                                    style={{
                                        margin: 0,
                                        height: contentHeight,
                                        overflow: "auto"
                                    }}
                                >
                                    <UserRoutes />
                                </Content>
                            </Layout>
                        </Layout>
                }

            </Layout>
        </HomeAllBOx>
    );
};

export default Home;
